package com.hkyp.ss.course.apis.utils;


import com.hkyp.ss.course.apis.exception.APIException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: SendEmailUtil
 * @Description: 发送邮箱验证码
 * @Author:
 * @CreateDate: 2018/6/16 11:47
 * @Version: 1.0
 */
@Component
@Slf4j
public class SendEmailUtil {

    @Value("${email.util.apiUser}")
    private String apiUser;//账号
    @Value("${email.util.apiKey}")
    private String apiKey;//密码
    @Value("${email.util.url}")
    private String url;

    public boolean send(String address, String vCode) {
        try {
            HttpPost httpPost = new HttpPost(url);
            CloseableHttpClient httpClient = HttpClients.createDefault();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("apiUser", apiUser));
            params.add(new BasicNameValuePair("apiKey", apiKey));
            params.add(new BasicNameValuePair("to", address));
            //MNHI1GBcoQlQLzfw5JNCjYLRcTKHsY1.sendcloud.org是发信域名，“@”之前的自己定义
            params.add(new BasicNameValuePair("from", "bsom@sMNHI1GBcoQlQLzfw5JNCjYLRcTKHsY1.sendcloud.org"));
            params.add(new BasicNameValuePair("fromName", "学渣乐园"));
            params.add(new BasicNameValuePair("subject", "来自学渣乐园的验证码"));
            params.add(new BasicNameValuePair("html",
                    "欢迎加入学渣乐园！\n" + "注册验证码："
                            + vCode
                            + "请在20分钟内使用。（请确保是本人操作，否则请忽略）\n" + "--学渣乐园\n"
                            + "（这是一封自动产生的email，请勿回复。）\n" ));
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            // 处理响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 正常返回, 解析返回数据
                log.info("发送成功，返回数据：{}", EntityUtils.toString(response.getEntity()));
                return true;//发送成功
            } else {
                log.info("error");
            }
            httpPost.releaseConnection();
        } catch (Exception e){
            e.printStackTrace();
            log.info("发送邮件出错：{}", e.getMessage());
            APIException exception = new APIException("发送邮件验证码出错" + e.getMessage());
            exception.initCause(e);
            throw exception;
        }
        return false;//发送失败
    }
}
